<!--
 * @Description: 接口管理-新建接口
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-09-26
-->
<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestSaveInterface } from '/@/api/system/ysys-user/interface'
  import { InterfaceTypeEnum } from '/@/api/system/ysys-user/interface/enum'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const props = defineProps({
    visible: { type: Boolean, default: false },
    pId: { type: Number, default: NaN },
    pName: { type: String, default: '' },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal) => {
      if (newVal) onPageshow()
      else onPageHide()
    },
  )

  /**
   * 页面显示
   */
  const onPageshow = () => {}

  /**
   * 页面关闭
   */
  const onPageHide = () => resetFields()

  /** 表单配置 */
  const form = reactive({
    state: {
      /** 接口名称 */
      interfaceName: '',
      /** 接口地址 */
      interfaceUri: '',
      /** 备注 */
      interfaceDesc: '',
    },
    rule: {
      interfaceName: [{ required: true, message: '请输入接口名称' }],
    },
    onOk: () => {
      validate()
        .then(async () => {
          const { interfaceName, interfaceUri, interfaceDesc } = form.state
          const { responseCode } = await requestSaveInterface({ interfacePId: props.pId, interfacePName: props.pName, interfaceName, interfaceUri, interfaceDesc, interfaceType: InterfaceTypeEnum.INTERFACE })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('添加成功')
            visible.value = false
            emits('success')
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, validateInfos, resetFields } = Form.useForm(form.state, form.rule)
</script>

<template>
  <div class="interface-add">
    <a-modal v-model:visible="visible" title="新建接口" @ok="form.onOk">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="所属分组" v-if="!isNaN(props.pId)">
          <a-input :value="props.pName" disabled />
        </a-form-item>
        <a-form-item label="接口名称" v-bind="validateInfos.interfaceName">
          <a-input v-model:value="form.state.interfaceName" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="接口地址" v-bind="validateInfos.interfaceUri">
          <a-input v-model:value="form.state.interfaceUri" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="备注" v-bind="validateInfos.interfaceDesc">
          <a-input v-model:value="form.state.interfaceDesc" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped></style>
